package com.jinzhi.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.Tree;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.oss.domain.FileDO;
import com.jinzhi.oss.service.FileService;
import com.jinzhi.sys.domain.MenuDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.MenuService;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * </pre>
 * <small> 2018年3月23日 | Aron</small>
 */
@Controller
@AllArgsConstructor
public class AdminController extends BaseController {

    private MenuService menuService;
    private FileService fileService;
    private MpConfigService mpConfigService;
    private UserRoleService userRoleService;
    private RoleService roleService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    UserService userService;
    @Autowired
    private ExaminationRoomService examinationRoomService;
    @Autowired
    private PersonnelArrangementService personnelArrangementService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private CapitalFlowService capitalFlowService;

    @GetMapping({"/", ""})
    String welcome(Model model) {
        return "redirect:/login";
    }

    @GetMapping({"/index"})
    String index(Model model) {
        Long userId = getUserId();
        List<Tree<MenuDO>> menus = menuService.listMenuTree(userId);
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        model.addAttribute("username", getUser().getUsername());
        FileDO fileDO = fileService.selectById(getUser().getPicId());
        model.addAttribute("picUrl", fileDO == null ? "/img/photo_j.jpg" : fileDO.getUrl());
        List<MpConfigDO> mpList = mpConfigService.selectList(null);
        model.addAttribute("mpList", mpList);
        return "index_v1";
    }

    @GetMapping("/login")
    String login() {
        return "login2";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    Result<?> ajaxLogin(String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

//        token.setRememberMe(false);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //获得用户信息
            UserDO userDO = (UserDO) subject.getPrincipals().getPrimaryPrincipal();

            //查询用户角色
            String roleName = getRoleNames();
//            if ((roleName.contains("考评员")) || (roleName.contains("督导员"))) {
//                if (userDO.getOrgId() != null){
//
//                    List<OrganizationRolesDO> orgList = organizationRolesService.findByKv("applicant_id" , this.getUserId());
//
//                    if (orgList.size() >= 1) {
//                        return Result.ok();
//                    }else {
//                        ExpertsDO expert = expertsService.findOneByKv("user_id" , userDO.getId());
//                        if (expert != null){
//                            List list = new ArrayList();
//                            List<PersonnelArrangementDO> paDoList = personnelArrangementService.findByKv("user_id" , this.getUserId());
//                            for (PersonnelArrangementDO paDo :paDoList){
//                                CertificationBatchDO cBatch = certificationBatchService.selectById(paDo.getCbatchId());
//                                if (cBatch.getState() != 9){
//                                    OrganizationNewsDO org = organizationNewsService.selectById(paDo.getOrgId());
//                                    if (org != null){
//                                        list.add(org);
//                                    }
//                                }
//                            }
//                            return Result.ok(list);
//                        }else {
//                            subject.logout();
//                            return Result.build(EnumErrorCode.have_no_right.getCode(), EnumErrorCode.have_no_right.getMsg());
//                        }
//                    }
//
//                }else {
//                    subject.logout();
//                    return Result.build(EnumErrorCode.have_no_right.getCode(), EnumErrorCode.have_no_right.getMsg());
//                }
//            }else {
                return Result.ok();
           // }

        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
        }
    }

    @Log("存储用户选择的机构")
    @PostMapping("/org")
    @ResponseBody
    Result<String> org(Long orgId , HttpServletRequest req) {

        /*HttpSession session = req.getSession();
        session.setAttribute("orgId", orgId);*/

        req.getSession().setAttribute("orgId" , orgId);

        return Result.ok();
    }


    @GetMapping("/main")
    String main(Model model , HttpServletRequest req) {
        UserDO userDO = userService.selectById(this.getUserId());
        model.addAttribute("name", userDO.getUsername());
        model.addAttribute("orgName", userDO.getOrgName());

        List<String> roleNames = userRoleService.selroleNameList(this.getUserId());
        model.addAttribute("roleNames", roleNames);
        req.getSession().setAttribute("roleNames" , roleNames);

        EntityWrapper entityWrapper = new EntityWrapper();
        int stuAllNum;
        int eroomAllNum;
        if(roleNames.indexOf("超级用户角色") > -1) {
            stuAllNum = stuSignUpService.selectCount(entityWrapper);
            eroomAllNum = examinationRoomService.selectCount(entityWrapper);

            int orgAllNum = organizationRolesService.selectCount(entityWrapper);
            model.addAttribute("orgAllNum",orgAllNum);

            int expAllNum = expertsService.selectCount(entityWrapper);
            model.addAttribute("expAllNum",expAllNum);

            int stuNoReview = stuSignUpService.selNoReviewAll();
            model.addAttribute("stuNoReview",stuNoReview);
            int orgNoReview = organizationRolesService.selNoReviewAll();
            model.addAttribute("orgNoReview",orgNoReview);
            int expNoReview = expertsService.selNoReviewAll();
            model.addAttribute("expNoReview",expNoReview);
            int eroomNoReview = examinationRoomService.selNoReviewAll();
            model.addAttribute("eroomNoReview",eroomNoReview);
        }else{
            stuAllNum = stuSignUpService.selNoReview(this.getUser().getOrgId());
            eroomAllNum = examinationRoomService.selNoReview(this.getUser().getOrgId());
        }
        model.addAttribute("stuAllNum",stuAllNum);
        model.addAttribute("eroomAllNum",eroomAllNum);

        return "main";
    }

    @GetMapping("/403")
    String error403() {
        return "403";
    }


    @Log("查询系统收入")
    @PostMapping("/earning")
    @ResponseBody
    Result<?> earning(HttpServletRequest req) {

        Object obj = req.getSession().getAttribute("roleNames");

        String objs = obj.toString().replace("[", "").replace("]" ,"");
        String[] roleNames = objs.split(",");

        for (int i= 0; i < roleNames.length; i++){
            if (roleNames[i] == "超级用户角色" || roleNames[i].equals("超级用户角色")){
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Map map = new HashMap();

                BigDecimal capitalDay = new BigDecimal(0.00);
                BigDecimal capitalCount = new BigDecimal(0.00);
                //查询当日收入
                List<CapitalFlowDO> capitalDayList = capitalFlowService.findByKv("signs" , 1 , "creater_date" , formatter.format(new Date()) , "state" , 0);
                for (CapitalFlowDO capitalFlowDO: capitalDayList){
                    capitalDay = capitalDay.add(capitalFlowDO.getMoney());
                }
                //查询总收入
                List<CapitalFlowDO> capitalCountList = capitalFlowService.findByKv("signs" , 1, "state" , 0);
                for (CapitalFlowDO capitalFlowDO: capitalCountList){
                    capitalCount = capitalCount.add(capitalFlowDO.getMoney());
                }

                map.put("capitalDay" , capitalDay);
                map.put("capitalCount" , capitalCount);
                return Result.ok(map);
            }
        }
        return Result.fail();
    }

}